var app = getApp()
Page({
  data: {
    sets: [],
    page:0,
    firstRefresh:false,
    isLoading:false
  },
  onLoad(options) {
    wx.setNavigationBarTitle({ title:"我的动态" })
    wx.cloud.callFunction({
      name: 'function',
      data: {
        type: "getPost",
        page:0,
        where: {
          user_id: app.globalData.database._id
        }
      }
    }).then(res => {
      this.setData({
        sets: res.result.user.data
      })
      this.setData({ page: 0, firstRefresh: true })
    })
  },
  click(a) {
    var that = this
    wx.showActionSheet({
      itemList: ['查看', '删除(删除图文评论)'],
      success: function (res) {
        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: '../home/postView?postId=' + a.currentTarget.dataset.id
          })
        } else if (res.tapIndex == 1) {
          wx.cloud.callFunction({
            name: 'function',
            data: {
              type: "deletePost",
              id: a.currentTarget.dataset.id
            }
          })
          var d = new Array()
          for (var i = 0; i < that.data.sets.length; i++) {
            if (that.data.sets[i]._id != a.currentTarget.dataset.id) {
              d.push(that.data.sets[i])
            }
          }
          that.setData({
            sets: d
          })
        }
      }
    })
  }, 
  onPullDownRefresh: function () {
    wx.cloud.callFunction({
      name: 'function',
      data: {
        type: "getPost",
        page:0,
        where: {
          user_id: app.globalData.database._id
        }
      }
    }).then(res => {
      this.setData({
        sets: res.result.user.data
      })
      this.setData({ page: 0, firstRefresh: true })
      wx.stopPullDownRefresh()
    })
  }, onReachBottom() {
    if ((!this.data.isLoading) && this.data.firstRefresh) {
      this.setData({ isLoading: true, page: this.data.page + 1 })
      wx.cloud.callFunction({ name: 'function', data: { type: "getPost", page: this.data.page,where:{user_id: app.globalData.database._id}} }).then(res => {
        if (res.result.user.data.length < 10) {
          this.setData({ page: this.data.page })
        }
        var set = this.data.sets
        this.setData({
          sets: set.concat(res.result.user.data)
        })
        this.setData({ isLoading: false })
      })
    }
  }
})